import fs, {Stats} from "node:fs";
import KoaBootFile from "../web/KoaBootFile";
import KoaBootLogger from "@framework/web/KoaBootLogger";

/**
 * 类路径扫描
 */
class ClassPathBeanDefinitionScanner {

    /**
     * 日志
     * @private
     */
    private readonly logger: KoaBootLogger = KoaBootLogger.getInstance();

    /**
     * 读取扫描目录集合
     * @param classPath
     */
    public readFilePath(classPath: string): Array<string> {
        this.logger.debug("Loader Work Directory ...")
        const fileList = new Array<string>();
        this.scanner(classPath, fileList);
        return fileList;
    }

    /**
     * 扫描工作目录
     * @param path 扫描路径
     * @param fileList 文件模块集合
     */
    private scanner(classPath: string, fileList: Array<string>): void {
        if (this.isFile(classPath)) {
            return;
        }
        const dirnameList: string[] = fs.readdirSync(classPath);
        for(let dirname of dirnameList) {
            const file = new KoaBootFile(classPath, dirname);
            const newPath: string = file.getPath();
            if (this.isFile(newPath) && newPath.endsWith(".ts") && !newPath.endsWith(".d.ts")) {
                this.logger.debug("Loader Resource Path: " + newPath);
                fileList.push(newPath);
                continue;
            }
            this.scanner(newPath, fileList);
        }
    }

    /**
     * 判断此路径是否是文件
     * @param path 判断是否是文件
     * @returns true 是 false 不是
     */
    private isFile(path: string): boolean | undefined {
        try {
            const stats: Stats = fs.statSync(path);
            return stats.isFile();
        } catch(e) {
            return false;
        }
    }
}

export default ClassPathBeanDefinitionScanner;